# -*- coding: utf-8 -*-
# @Time    : 2018-05-28 21:51
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : SettledLoansNum_of_NoOverdue.py
# @Software: PyCharm

'''eof
name:已结清无逾期发生贷款笔数
code:SettledLoansNum_of_NoOverdue
tableName:
columnName:
groups:个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']


def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def SettledLoansNumOfNoOverdue():
    try:
        icrLoanInfo002LoanList = FormatData("ICRLoanInfo002*Loan")
        ICRLatest5YearOverdueDetailLoanList = FormatData("ICRLatest5YearOverdueDetail*Loan")
        if icrLoanInfo002LoanList == [{}] and ICRLatest5YearOverdueDetailLoanList == [{}]:
            return u'缺失值'
        else:
            returnList = []
            accountList = []
            for ICRLatest5YearOverdueDetailLoan in ICRLatest5YearOverdueDetailLoanList:
                try:
                    account = ICRLatest5YearOverdueDetailLoan.get('Account')
                    if account not in null_type_list:
                        accountList.append(account)
                except:
                    continue

            for icrLoanInfo002Loan in icrLoanInfo002LoanList:
                try:
                    # 账户状态
                    state = icrLoanInfo002Loan.get('State')
                    # 业务号码
                    accountLil = icrLoanInfo002Loan.get('Account')
                    if state in null_type_list or accountLil in null_type_list:
                        returnList.append(None)
                        continue
                    if state in (u"结清", u"转出") and accountLil not in accountList:
                        returnList.append(1)
                    else:
                        returnList.append(0)
                except:
                    returnList.append(None)
                    continue
            returnListNotNone = filter(lambda x:x is not None, returnList)
            if len(returnListNotNone) == 0:
                return u'缺失值'
            else:
                return sum(returnListNotNone)
    except:
        return u'缺失值'


result = SettledLoansNumOfNoOverdue()
